<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Jobs\ExcelTaskController;
use App\Libs\wrapper\Role;

//千易
class QianyiModel extends BaseModel
{

    protected $appId    = '15659560858';
    protected $vision = 'v1';
    protected $url = 'https://www.qianyierp.com/api/v1/';
    protected $privateKey = 'EXYGTYBWLGHKTLWVGQDFOBEHBNLYSK';



    public function TestM($params)
    {
        $data['bizParam'] = [
            'page' => 1, // 页码  
            'pageSize' => 10, // 每页条数  
        ];

        $data['serviceType'] = 'QUERY_WAREHOUSE_LIST';
        $data['api_name'] = 'warehouse';
        $return = $this->GetQianyi($data);

        if($return['type']=='success'){
            // Redis::Set('qianyi',json_encode($return['data']));
            return $this->SBack($return['data']);
        }else{
            return $this->FailBack($return['msg']);
        }
 
    }

    public function UpPurchaseOrderM($params){
        $purchaseNumber = $params['purchaseNumber'];
        if(is_array($params['ratio'])){
            $ratio = [];
            foreach ($params['ratio'] as $rv) {
                # code...
                $ratio[$rv['key']] = $rv['value'];
            }
            db::table('cloudhouse_custom_sku')->where('contract_no',$purchaseNumber)->update(['ratio'=>json_encode($ratio)]);
        }

        return ['type'=>'success','data'=>[]];

    }
    //查询采购单
    public function PurchaseOrderListTotalM($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')->groupby('a.contract_no');
        if(isset($params['sku'])){
            $list = $list->where('a.sku','like','%'.$params['sku'].'%');
        }

    
        if(isset($params['purchaseNumber'])){
            $list = $list->where('a.contract_no','like','%'.$params['purchaseNumber'].'%');
        }


        $totalNum = $list->get()->count();
        // DB::connection()->enableQueryLog();
        $list = $list->offset($page)->limit($limit)->select('a.*',db::raw('group_concat(custom_sku) as skus'),db::raw('sum(num) as purchaseQuantity'),'b.supplier_short_name','b.create_time as createTime')->get();

        foreach ($list as $v) {
            # code...

                $ratio = json_decode($v->ratio,true);
                $ratio_arr = [];

                if(is_array($ratio)){
                    foreach ($ratio  as $platform_id => $ratio_num) {
                        # code...
                        $ratio_one['platform_id'] =$platform_id;
                        $ratio_one['platform'] = $this->GetPlatform($platform_id)['name'];
                        $ratio_one['ratio_num'] = $ratio_num;
                        $ratio_arr[] =  $ratio_one;
    
                    }
                }
  
                $v->ratio = $ratio_arr;
               //合同数量 
                // 未出货数量 goods_transfers_detail  合同数 - receive_num  状态未完成 = 合同数-transfers_num
                // 已出货待入库数量 transfers_num-receive_num
                // 已入库数量receive_num  type_detail = 2(出货)   - type_detail = 9（退货）
                $un_outnum = 0;
                $wait_outnum = 0;
                $receive_num = 0;

                $goods_transfers_detail = db::table('goods_transfers_detail as a')
                ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
        //            ->where('b.contract_no','like','%'.$v->contract_no.'%')
                ->whereIn('b.is_push',[1,2,3,4])
                ->where('b.type_detail', 9)
                ->where('a.contract_no',$v->contract_no)
                ->get(['a.*', 'b.is_push']);


                if($goods_transfers_detail->isNotEmpty()){
                    foreach ($goods_transfers_detail as $g_t_d_v) {
                        # code...
                        //已完成
                        $un_outnum+=$g_t_d_v->receive_num;
                        $wait_outnum+=$g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                        $receive_num =  $g_t_d_v->receive_num;
                    }
                }

                //已入库 = 
                $v->v_receive_num =  $receive_num;
                //未出货
                $v->v_un_outnum = $v->purchaseQuantity - $receive_num -$wait_outnum;
                //已出货待入库数量
                $v->v_wait_outnum = $wait_outnum;


                $v->asnNumber ='';
                // $v->createTime = '';
                $v->purchaseDate = '';
                $v->purchaseNumber = $v->contract_no;
                $v->remark = '';
                $v->supplierName = $v->supplier_short_name;
                $v->warehouseName = '';
                $v->purchasePrice = $v->price;
                $v->purchaseQuantity = $v->purchaseQuantity;
                $v->title = $v->name;
        }

        $return['total_num'] = $totalNum;
        $return['list'] = $list;
        return $this->SBack($return);
    }



    //查询采购单
    public function PurchaseOrderListM($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = db::table('cloudhouse_custom_sku as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->leftjoin('self_spu as c','b.spu_id','=','c.id')->leftjoin('cloudhouse_contract_total as d','a.contract_no','=','d.contract_no');
        $list = $list->where('b.id','>',0);
        if(isset($params['sku'])){
            $list = $list->where(function($query) use($params){
                $query->where('b.custom_sku','like','%'.$params['sku'].'%')
                    ->orwhere('b.old_custom_sku','like','%'.$params['sku'].'%');
            });
        }

        if(isset($params['purchaseNumber'])){
            $list = $list->where('a.contract_no','like','%'.$params['purchaseNumber'].'%');
        }

        $totalNum = $list ->count();
        // DB::connection()->enableQueryLog();
        $list = $list->offset($page)->limit($limit)->select('a.*','b.size','b.color','b.old_custom_sku','c.spu','c.old_spu','d.supplier_short_name','d.create_time as createTime')->get();

        foreach ($list as $v) {

            $ratio = json_decode($v->ratio,true);
            $ratio_arr = [];

            if(is_array($ratio)){
                foreach ($ratio  as $platform_id => $ratio_num) {
                    # code...
                    $ratio_one['platform_id'] =$platform_id;
                    $ratio_one['platform'] = $this->GetPlatform($platform_id)['name'];
                    $ratio_one['ratio_num'] = $ratio_num;
                    $ratio_arr[] =  $ratio_one;

                }
            }

            $v->ratio = $ratio_arr;
            # code...
            if($v->old_custom_sku){
                $v->custom_sku = $v->old_custom_sku;
            }
            if($v->old_spu){
                $v->spu = $v->old_spu;
            }

               //合同数量 
                // 未出货数量 goods_transfers_detail  合同数 - receive_num  状态未完成 = 合同数-transfers_num
                // 已出货待入库数量 transfers_num-receive_num
                // 已入库数量receive_num  type_detail = 2(出货)   - type_detail = 9（退货）
                $un_outnum = 0;
                $wait_outnum = 0;
                $receive_num = 0;

                $goods_transfers_detail = db::table('goods_transfers_detail as a')
                ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
        //            ->where('b.contract_no','like','%'.$v->contract_no.'%')
                ->whereIn('b.is_push',[1,2,3,4])
                ->where('b.type_detail', 2)
                ->where('a.contract_no',$v->contract_no)
                ->where('a.custom_sku_id',$v->custom_sku_id)
                ->get(['a.*', 'b.is_push']);

                $v->purchaseQuantity = $v->num;
                if($goods_transfers_detail->isNotEmpty()){
                    foreach ($goods_transfers_detail as $g_t_d_v) {
                        # code...
                        //已完成
                        $un_outnum+=$g_t_d_v->receive_num;
                        $wait_outnum+=$g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                        $receive_num =  $g_t_d_v->receive_num;
                    }
                }

                //已入库 = 
                $v->v_receive_num =  $receive_num;
                //未出货
                $v->v_un_outnum = $v->purchaseQuantity - $receive_num -$wait_outnum;
                //已出货待入库数量
                $v->v_wait_outnum = $wait_outnum;

                $v->purchaseNumber = $v->contract_no;

                $v->asnNumber ='';
                // $v->createTime = '';
                $v->purchaseDate = '';
                $v->purchaseNumber = $v->contract_no;
                $v->remark = '';
                $v->supplierName = $v->supplier_short_name;
                $v->warehouseName = '';
                $v->purchasePrice = $v->price;

                $v->title = $v->name;
                $v->sku = $v->custom_sku;

        }

        $return['total_num'] = $totalNum;
        $return['list'] = $list;
        return $this->SBack($return);
    }

    public function UpdateSpuid(){
        $list = db::table('purchase_order_list')->where('custom_sku_id',0)->get();
        foreach ($list as $v) {
            # code...
            $cus = db::table('self_custom_sku')->where('custom_sku',$v->sku)->orwhere('old_custom_sku',$v->sku)->first();
            if($cus){
                $custom_sku_id = $cus->id;
                $spu_id = $cus->spu_id;
                db::table('purchase_order_list')->where('id',$v->id)->update(['custom_sku_id'=>$custom_sku_id,'spu_id'=>$spu_id]);
            }
        }
    }

    public function AddContract($params){

        $contract_no = $params['purchaseNumber'];
        $supplier_short_name = $params['supplierName'];
        $one_price = $params['purchasePrice'];
        $num = $params['purchaseQuantity'];
        $custom_sku = $params['sku'];
        $title = '';

        $custom_sku_id = 0;
        $spu_id = 0;
        $spu = '';
        $supplier_id = 0;
        $color_identifying = '';
        $color_name = '';

        $time = date('Y-m-d H:i:s',time());

        $cus = db::table('self_custom_sku')->where('custom_sku','like','%'.$custom_sku.'%')->orwhere('old_custom_sku','like','%'.$custom_sku.'%')->first();

        // Redis::Hset('a',$custom_sku,json_encode($cus));
        if(!$cus){
            return;
        }

        $spu = $cus->spu;
        $custom_sku_id = $cus->id;
        $spu_id = $cus->spu_id;
        $title  =  $cus->name;
        $color_identifying  = $cus->color;
        $color_name = db::table('self_color_size')->where('identifying',$cus->color)->first()->name;
        $size = $cus->size;
        $supplier_no = '';
        $supplier = db::table('suppliers')->where('name',$supplier_short_name)->first();
        if($supplier){
            $supplier_id = $supplier->Id;
            $supplier_no =  $supplier->supplier_no;
        }

        $c_repeat = db::table('cloudhouse_contract')->where('spu_id',$spu_id)->where('contract_no',$contract_no)->where('color_identifying',$color_identifying)->first();

        $t_repeat = db::table('cloudhouse_contract_total')->where('contract_no',$contract_no)->first();

        $cus_repeat = db::table('cloudhouse_custom_sku')->where('contract_no',$contract_no)->where('custom_sku_id',$custom_sku_id)->first();

        if($cus_repeat){
            $cus_i['num'] = $num;
            db::table('cloudhouse_custom_sku')->where('id',$cus_repeat->id)->update($cus_i);
        }else{
            $cus_i['spu'] = $spu;
            $cus_i['spu_id'] = $spu_id;
            $cus_i['name'] = $title;
            $cus_i['price'] = $one_price;
            $cus_i['size'] = $size;
            $cus_i['color'] = $color_identifying;
            $cus_i['contract_no'] = $contract_no;
            $cus_i['custom_sku'] = $custom_sku;
            $cus_i['custom_sku_id'] = $custom_sku_id;
            $cus_i['num'] = $num;
            $cus_i['color_name'] = $color_name;
            $cus_i['order_detail'] = round($one_price*$num,2);
            db::table('cloudhouse_custom_sku')->insert($cus_i);
        }

        if($c_repeat){
            $num_info = json_decode($c_repeat->num_info);

            if(!isset($num_info)){
                $num_info[$size] = $num;
                $c_u['count'] = $c_repeat->count+$num;
                $c_u['price'] = round($c_repeat->price+$one_price*$num,2);
                $c_u['num_info'] = json_encode($num_info);
                db::table('cloudhouse_contract')->where('id',$c_repeat->id)->update($c_u);
            }
        

        }else{
            $c_i['spu'] = $spu;
            $c_i['spu_id'] = $spu_id;
            $c_i['title'] = $title;
     
            $c_i['one_price'] = $one_price;
    
            $c_i['contract_no'] = $contract_no;
            $c_i['status'] = 1;
            $c_i['type'] = 1;
            $c_i['create_user'] = 1;
            $c_i['create_time'] = $time;
            $c_i['sign_date'] = $time;
            $c_i['house_type'] = 2;
            $c_i['color_identifying'] = $color_identifying;
            $c_i['color_name'] = $color_name;
            $c_i['num_info'] = json_encode([$size=>$num]);
            $c_i['rule'] = $size;
            $c_i['count'] = $num;
            $c_i['price'] = round($one_price*$num,2);
            db::table('cloudhouse_contract')->insert($c_i);
        }


        if($t_repeat){
            $t_i['total_count'] = db::table('cloudhouse_contract')->where('contract_no',$contract_no)->groupby('spu_id')->count();
            $t_i['total_price'] =  db::table('cloudhouse_contract')->where('contract_no',$contract_no)->sum('price');
            $t_i['spu_count'] = db::table('cloudhouse_contract')->where('contract_no',$contract_no)->count();
            db::table('cloudhouse_contract_total')->where('id',$t_repeat)->update($t_i);
        }else{
            $t_i['contract_class'] = 1;
            $t_i['updated_at'] =  $time;
            $t_i['create_time'] =  $time;
            $t_i['sign_date'] =  $time;
            $t_i['sign_date'] =  $time;
            $t_i['is_end'] = 1;
            $t_i['status'] = 1;
            $t_i['contract_status'] = 2;
            $t_i['contract_type'] = 1;
            $t_i['supplier_short_name'] =  $supplier_short_name;
            $t_i['supplier_id'] = $supplier_id;
            $t_i['supplier_no'] = $supplier_no;
            $t_i['contract_no'] = $contract_no;
            $t_i['total_count'] = db::table('cloudhouse_contract')->where('contract_no',$contract_no)->groupby('spu_id')->count();
            $t_i['total_price'] =  db::table('cloudhouse_contract')->where('contract_no',$contract_no)->sum('price');
            $t_i['spu_count'] = db::table('cloudhouse_contract')->where('contract_no',$contract_no)->count();
            db::table('cloudhouse_contract_total')->insert($t_i);
        }
  
        return;
    }

    //采集采购单
    public function PurchaseOrderM(){

        $data['bizParam'] = [
            'page' => 1, // 页码  
            'pageSize' => 200, // 每页条数  
        ];

        // $start_time = '2024-03-25';
        // $end_time = '2024-03-27';
        $start_time = date('Y-m-d',time()-86400*1);
        $end_time = date('Y-m-d',time());
        $data['bizParam'] = [
            // 'purchaseNumber' => 1, // 采购单号  
            // 'status' => 10, // NEW	采购单状态  
            'updateTimeFrom' => $start_time, // 更新时间 （范围开始）
            'updateTimeTo' => $end_time, //更新时间（范围结束）  
        ];

        $data['serviceType'] = 'QUERY_PURCHASE_ORDER_LIST';
        $data['api_name'] = 'purchase';
        $return = $this->GetQianyi($data);
 
        if($return['type']=='success'){


            $result = json_decode($return['data']['bizContent'],true)['result'];
           
            $total_num =  json_decode($return['data']['bizContent'],true)['total'];

            if($total_num>=200){
                $this->PurchaseOrderMb(['page'=>2,'start_time'=>$start_time,'end_time'=>$end_time]);
            }

            foreach ($result as $rv) {
                # code...
                if(isset($rv['asnNumber'])){
                    $i['asnNumber'] = $rv['asnNumber'];//入库单号
                    $q['asnNumber'] = $rv['asnNumber'];//入库单号
                }
                $i['createTime'] = $rv['createTime'];//
                $i['purchaseDate'] = $rv['purchaseDate'];//创建时间
                $i['purchaseMode'] = $rv['purchaseMode'];//采购模式EASYWAY：简单模式STANDARD：标准模式
                $i['purchaseNumber'] = $rv['purchaseNumber'];//采购单号
                $q['purchaseNumber'] = $rv['purchaseNumber'];//采购单号
                $i['purchasePriceUnit'] = $rv['purchasePriceUnit'];//币种
                $i['purchaseType'] = $rv['purchaseType'];//TRANSFER：海外仓采购 DIRECT：国内仓采购
                $i['remark'] = $rv['remark']??'';//备注
                $i['settlementType'] = $rv['settlementType'];//结算方式DELIVERY_ON_CASH：带款提货FIXED_ACCOUNT_PERIOD：固定账期DYNAMIC_ACCOUNT_PERIO
                $i['shippingCost'] = $rv['shippingCost'];//运费
                $i['status'] = $rv['status'];//采购单状态NEW新建 WAIT_CHECK	待审核  WAIT_REVIEW	待复审DENIED审核不通过APPROVED	审核通过ORDERED	已下单RECEIVING	收货中CLOSED已关闭FINISH	已完成
                $i['supplierName'] = $rv['supplierName'];//供应商
                $i['transferWarehouseName'] = $rv['transferWarehouseName'];//中转仓
                $i['updateTime'] = $rv['updateTime'];//
                $i['warehouseName'] = $rv['warehouseName'];//采购仓
                foreach ($rv['skuList'] as $rov) {
                    # code...
                    $i['purchasePrice'] = $rov['purchasePrice'];//采购价格
                    $i['purchaseQuantity'] = $rov['purchaseQuantity'];//采购数量
                    $i['sku'] = $rov['sku'];//
                    $q['sku'] = $rov['sku'];//
                    $i['taxRate'] = $rov['taxRate'];//采购税率
                    $i['title'] = $rov['title'];//商品名称
                   $repeat =  db::table('purchase_order_list')->where($q)->first();
                   if($repeat){
                        db::table('purchase_order_list')->where('id',$repeat->id)->update($i);
                   }else{
                        db::table('purchase_order_list')->insert($i);
                   }


                   $add['purchaseNumber'] = $rv['purchaseNumber'];
                   $add['supplierName'] = $rv['supplierName'];
                   $add['purchasePrice'] = $rov['purchasePrice'];
                   $add['purchaseQuantity'] = $rov['purchaseQuantity'];
                   $add['sku'] = $rov['sku'];
                   try {
                    //code...
                    $this->AddContract($add);
                    Redis::Hset('contract_list',$i['purchaseNumber'].'-'.rand(1,5000),json_encode($add));
                   } catch (\Throwable $th) {
                    //throw $th;
                    $err['line'] = $th->getLine();
                    $err['msg'] = $th->getMessage();
                    Redis::Set('contract_err',json_encode($err));
                   }
           
                }
            }

            return $this->SBack($return);
        }else{
            return $this->FailBack($return['msg']);
        }
 

    }

       //采集采购单
       public function PurchaseOrderMb($params){

        $data['bizParam'] = [
            'page' => $params['page'], // 页码  
            'pageSize' => 200, // 每页条数  
        ];

        // $start_time = '2024-03-25';
        // $end_time = '2024-03-27';
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $data['bizParam'] = [
            // 'purchaseNumber' => 1, // 采购单号  
            // 'status' => 10, // NEW	采购单状态  
            'updateTimeFrom' => $start_time, // 更新时间 （范围开始）
            'updateTimeTo' => $end_time, //更新时间（范围结束）  
        ];

        $data['serviceType'] = 'QUERY_PURCHASE_ORDER_LIST';
        $data['api_name'] = 'purchase';
        $return = $this->GetQianyi($data);

        if($return['type']=='success'){


            $result = json_decode($return['data']['bizContent'],true)['result'];

            $total_num = $return['data']['total'];

            if($total_num>=200){
                $this->PurchaseOrderM(2);
            }

            foreach ($result as $rv) {
                # code...
                if(isset($rv['asnNumber'])){
                    $i['asnNumber'] = $rv['asnNumber'];//入库单号
                    $q['asnNumber'] = $rv['asnNumber'];//入库单号
                }
                $i['createTime'] = $rv['createTime'];//
                $i['purchaseDate'] = $rv['purchaseDate'];//创建时间
                $i['purchaseMode'] = $rv['purchaseMode'];//采购模式EASYWAY：简单模式STANDARD：标准模式
                $i['purchaseNumber'] = $rv['purchaseNumber'];//采购单号
                $q['purchaseNumber'] = $rv['purchaseNumber'];//采购单号
                $i['purchasePriceUnit'] = $rv['purchasePriceUnit'];//币种
                $i['purchaseType'] = $rv['purchaseType'];//TRANSFER：海外仓采购 DIRECT：国内仓采购
                $i['remark'] = $rv['remark']??'';//备注
                $i['settlementType'] = $rv['settlementType'];//结算方式DELIVERY_ON_CASH：带款提货FIXED_ACCOUNT_PERIOD：固定账期DYNAMIC_ACCOUNT_PERIO
                $i['shippingCost'] = $rv['shippingCost'];//运费
                $i['status'] = $rv['status'];//采购单状态NEW新建 WAIT_CHECK	待审核  WAIT_REVIEW	待复审DENIED审核不通过APPROVED	审核通过ORDERED	已下单RECEIVING	收货中CLOSED已关闭FINISH	已完成
                $i['supplierName'] = $rv['supplierName'];//供应商
                $i['transferWarehouseName'] = $rv['transferWarehouseName'];//中转仓
                $i['updateTime'] = $rv['updateTime'];//
                $i['warehouseName'] = $rv['warehouseName'];//采购仓
                foreach ($rv['skuList'] as $rov) {
                    # code...
                    $i['purchasePrice'] = $rov['purchasePrice'];//采购价格
                    $i['purchaseQuantity'] = $rov['purchaseQuantity'];//采购数量
                    $i['sku'] = $rov['sku'];//
                    $q['sku'] = $rov['sku'];//
                    $i['taxRate'] = $rov['taxRate'];//采购税率
                    $i['title'] = $rov['title'];//商品名称
                   $repeat =  db::table('purchase_order_list')->where($q)->first();
                   if($repeat){
                        db::table('purchase_order_list')->where('id',$repeat->id)->update($i);
                   }else{
                        db::table('purchase_order_list')->insert($i);
                   }


                   $add['purchaseNumber'] = $rv['purchaseNumber'];
                   $add['supplierName'] = $rv['supplierName'];
                   $add['purchasePrice'] = $rov['purchasePrice'];
                   $add['purchaseQuantity'] = $rov['purchaseQuantity'];
                   $add['sku'] = $rov['sku'];
                   try {
                    //code...
                    $this->AddContract($add);
                    Redis::Hset('contract_list',$i['purchaseNumber'].'-'.rand(1,5000),json_encode($add));
                   } catch (\Throwable $th) {
                    //throw $th;
                    $err['line'] = $th->getLine();
                    $err['msg'] = $th->getMessage();
                    Redis::Set('contract_err',json_encode($err));
                   }
           
                }
            }

            return $this->SBack($return);
        }else{
            return $this->FailBack($return['msg']);
        }
 

    }

    
    public function AddSkuM($params)
    {

        if(!isset($params['sku'])){
            return $this->FailBack('sku必传');
        }
        if(!isset($params['title'])){
            return $this->FailBack('品名必传');
        }
        if(!isset($params['weight'])){
            return $this->FailBack('毛重必传');
        }
        if(!isset($params['netWeight'])){
            return $this->FailBack('净重必传');
        }
        if(!isset($params['length'])){
            return $this->FailBack('长必传');
        }
        if(!isset($params['width'])){
            return $this->FailBack('宽必传');
        }
        if(!isset($params['height'])){
            return $this->FailBack('高必传');
        }

        if(isset($params['img'])){
            $data['bizParam']['picUrl'] = $params['img'];
        }

        $data['bizParam'] = [
            'sku' => $params['sku'], //sku
            'title' => $params['title'], //商品名称
            'weight' => $params['weight'], //毛重
            'netWeight' => $params['netWeight'], //净重
            'length' => $params['length'], //长
            'width' => $params['width'],//宽
            'height' => $params['height'],//高 
            'type' => 'SINGLE', //商品类型
            'weightUnit' => 'KG', //重量单位
            'dimensionUnit' => 'cm', //长度单位
            'enable' => 1, //商品状态（0:禁用;1:有效）
            'dangerousTransportGoodsType' => 'NONE',//危险品类型（NONE, LIQUID, POWDER, CONTAIN_ELECTRIC, ELECTRIC）
        ];

        // $data['bizParam'] = $params;

        // $data['bizParam'] = [
        //     'barcode' => 1, //商品条码

        //     'saleStatus' => '',//销售状态 否 
        //     'abbrTitle' => 1, //简称
        //     'brand' => 'KG', //品牌
        //     'unit' => 10, //单位
        //     'color' => 1, //颜色
        //     'size' => 'SINGLE', //尺码
        //     'itemPackage' => 1, //包装数量
        //     'description' => '商品描述，最大2048字符', //商品描述，最大2048字符
        //     'descriptionEn' => 'test', //商品描述英文，最大2048字符
        //     'functionDescription' => '性能描述，最大2048字符', //性能描述，最大2048字符
        //     'packingRate' => 1, //装箱率，若未填写则不保存外箱尺寸、外箱毛重、外箱净重等值
        //     'cartonLength' => 1, //外箱长度
        //     'cartonWidth' => 1, //外箱宽度
        //     'cartonHeight' => 1.2,//外箱高度
        //     'cartonWeight' => 10,//外箱毛重 
        //     'cartonNetWeight' => 10, //外箱净重
        //     'cartonDimensionUnit' => 'm', //外箱尺寸单位（cm; m）
        //     'cartonWeightUnit' => 'KG', //外箱重量单位（KG; G）
        //     'chineseCustomsDeclarationName' => '中文报关品名', //中文报关品名
        //     'englishCustomsDeclarationName' => 'KG', //英文报关品名
        //     'cdPriceMethod' => 'KG', //报关价格计算方式
        //     'cdPriceRate' => 1, //报关价格比例
        //     'cdPriceMaximum' => 12, //报关价格最大值
        //     'customsDeclarationPrice' => 10, //报关价格
        //     'customsDeclarationPriceUnit' => 'CNY', //报关价格单位（CNY; USD; CAD; GBP; EUR; JRY）
        //     'customsCode' => 'SINGLE', //海关编码
        //     'exportTax' => 1, //出口税率
        //     'declaration' => '',//申报说明
        //     'batteryType' => 0, //电池类型（0:不带电; 1:配套锂离子电池; 2:内置锂离子电池; 3:配套锂金属电池; 4:内置锂金属电池; 5:配套干电池）
        //     'ccPriceMethod' => 'KG', //清关价格计算方式
        //     'ccPriceRate' => 1, //清关价格比例
        //     'ccPriceMaximum' => 12, //清关价格最大值
        //     'ccPrice' => 10, //清关价格
        //     'ccPriceUnit' => 'CNY', //清关价格币种（CNY; USD; CAD; GBP; EUR; JRY）
        //     'needQualityInspection' => false,//是否需要质检
        //     'price' => 10,//默认售价 
        //     'priceUnit' => 'CNY', //默认售价单位（大写三位币种代码）
        //     'asin' => 'ASIN',//ASIN 
        //     'customProp1' => '自定义属性1', //自定义属性1
        //     'customProp2' => '自定义属性2',//自定义属性2
        //     'customProp3' => '自定义属性3', //自定义属性3
        //     'categoryName1' => '一级商品分类',//一级商品分类 
        //     'categoryName2' => '二级商品分类', //二级商品分类
        //     'categoryName3' => '三级商品分类',//三级商品分类 否 
        // ];

        $data['serviceType'] = 'INSERT_SKU_INFO';
        $data['api_name'] = 'sku';
        $return = $this->GetQianyi($data);
        $errorMsg = json_decode($return['data']['bizContent'],true);
  


        if($return['type']=='success'){
            if(!isset($errorMsg['errorMsg'])){
                return $this->SBack($errorMsg );
            }else{
                return $this->FailBack($errorMsg['errorMsg']);
            }

        }else{
            return $this->FailBack($return['msg']);
        }
 
    }



    public function GetQianyi($params){

        $bizParam = $params['bizParam'];
        $serviceType = $params['serviceType'];
        $api_name =  $params['api_name'];
        // 请求参数  
        $requestParams = [  
            'appId' => $this->appId, // 千易应用ID  
            'serviceType' => $serviceType, // 请求接口名  
            'bizParam'=>json_encode($bizParam),
            'timestamp' => time() * 1000, // 时间戳，单位毫秒   
        ];  
        
        // 私钥（从官方获取）  
        $privateKey = $this->privateKey;  
        
        // 生成签名  
        $requestParams['sign'] = $this->generateSignature($requestParams, $privateKey);  
        
        // API端点  
        $apiEndpoint = $this->url.$api_name;  


        // 初始化cURL会话  
        $ch = curl_init();  

        $q['url'] =  $apiEndpoint;
        $q['post'] =  $requestParams;
        Redis::Set('qianyisku',json_encode($q));

        curl_setopt($ch, CURLOPT_URL, $apiEndpoint);  
        curl_setopt($ch, CURLOPT_POST, true); // 启用POST请求  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestParams); // 设置POST参数  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回结果保存到变量中，而不是直接输出  
        
        // 执行请求并获取响应  
        $response = curl_exec($ch);  
        
        // 检查是否有错误发生  
        if (curl_errno($ch)) {  
            curl_close($ch);  
            return ['type'=>'fail','msg'=>curl_error($ch)];
        } else {  
            curl_close($ch);  
            $return = json_decode($response,true);
            if($return['state']=='success'){
                return ['type'=>'success','data'=>$return];
            }else{
                return ['type'=>'fail','msg'=>$return['errorCode'].$return['errorMsg']];
            }
      
        }  
        

    }


    public function generateSignature($params, $privateKey) {  
        // 剔除sign参数  
        if (isset($params['sign'])) {  
            unset($params['sign']);  
        }  
          
        // 参数排序  
        ksort($params);  
      
        // 生成签名字符串  
        $signString = '';  
        foreach ($params as $key => $value) {  
            $signString .= $key . '=' . $value;  
        }  
        $signString .= $privateKey; // 在字符串最后加上私钥  
      
        // 使用md5生成签名  
        return md5($signString); // 转换为大写，有些系统可能需要大写MD5  
    }  

    //成功返回
    public function SBack($data, $msg = '成功')
    {
        return ['type' => 'success', 'data' => $data, 'msg' => $msg];
    }

    //失败返回
    public function FailBack($msg)
    {
        return ['type' => 'fail', 'data' => [], 'msg' => $msg];
    }

    //获取当前毫秒
    function getMillisecond()
    {

        list($microsecond, $time) = explode(' ', microtime()); //' '中间是一个空格

        return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);

    }

    //超出字符数隐藏
    function cutSubstr($str, $len = 30)
    {
        if (strlen($str) > $len) {
            $str = substr($str, 0, $len) . '...';
        }
        return $str;
    }

    /**
     * 传入数组进行HTTP POST请求
     */
    function curlPost($url, $post_data = array(), $data_type = "")
    {
        $timeout = 5;
        $header  = empty($header) ? '' : $header;
        //支持json数据数据提交
        if ($data_type == 'json') {
            $post_string = json_encode($post_data);
        } elseif ($data_type == 'array') {
            $post_string = $post_data;
        } elseif (is_array($post_data)) {
            $post_string = http_build_query($post_data, '', '&');
        }

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        // curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回 
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_string))
        );

        $result = curl_exec($ch);

        // 打印请求的header信息
        //$a = curl_getinfo($ch);
        //var_dump($a);

        curl_close($ch);
        return $result;
    }

}